using Microsoft.Extensions.Logging;
using System;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using Microsoft.Extensions.DependencyInjection;

namespace DesktopHelper.Services
{
    public class TrayService
    {
        private readonly ILogger<TrayService> _logger;
        private readonly IServiceProvider _serviceProvider;
        private NotifyIcon? _notifyIcon;
        private ContextMenuStrip? _contextMenu;

        public TrayService(ILogger<TrayService> logger, IServiceProvider serviceProvider)
        {
            _logger = logger;
            _serviceProvider = serviceProvider;
        }

        public void Initialize()
        {
            try
            {
                CreateNotifyIcon();
                CreateContextMenu();
                _logger.LogInformation("系统托盘已初始化");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "系统托盘初始化失败");
            }
        }

        private void CreateNotifyIcon()
        {
            _notifyIcon = new NotifyIcon
            {
                Icon = GetApplicationIcon(),
                Text = "桌面助手",
                Visible = true
            };

            _notifyIcon.DoubleClick += OnTrayIconDoubleClick;
            _notifyIcon.MouseClick += OnTrayIconClick;
        }

        private void CreateContextMenu()
        {
            _contextMenu = new ContextMenuStrip();

            // 显示剪贴板历史
            var clipboardHistoryItem = new ToolStripMenuItem("剪贴板历史 (&H)")
            {
                Image = GetIcon("clipboard"),
                ShortcutKeyDisplayString = "Ctrl+Shift+V"
            };
            clipboardHistoryItem.Click += (s, e) => ShowClipboardHistory();

            // 截图菜单
            var screenshotItem = new ToolStripMenuItem("截图 (&S)")
            {
                Image = GetIcon("screenshot")
            };

            var regionScreenshotItem = new ToolStripMenuItem("区域截图 (&A)")
            {
                ShortcutKeyDisplayString = "Ctrl+Shift+A"
            };
            regionScreenshotItem.Click += (s, e) => TakeRegionScreenshot();

            var windowScreenshotItem = new ToolStripMenuItem("窗口截图 (&W)")
            {
                ShortcutKeyDisplayString = "Ctrl+Shift+W"
            };
            windowScreenshotItem.Click += (s, e) => TakeWindowScreenshot();

            var fullScreenshotItem = new ToolStripMenuItem("全屏截图 (&F)")
            {
                ShortcutKeyDisplayString = "Ctrl+Shift+S"
            };
            fullScreenshotItem.Click += (s, e) => TakeFullScreenshot();

            screenshotItem.DropDownItems.AddRange(new ToolStripItem[]
            {
                regionScreenshotItem,
                windowScreenshotItem,
                fullScreenshotItem
            });

            // 钉图管理
            var pinnedImagesItem = new ToolStripMenuItem("钉图管理 (&P)")
            {
                Image = GetIcon("pin")
            };

            var showAllPinnedItem = new ToolStripMenuItem("显示所有钉图 (&S)");
            showAllPinnedItem.Click += (s, e) => ShowAllPinnedImages();

            var hideAllPinnedItem = new ToolStripMenuItem("隐藏所有钉图 (&H)");
            hideAllPinnedItem.Click += (s, e) => HideAllPinnedImages();

            var closeAllPinnedItem = new ToolStripMenuItem("关闭所有钉图 (&C)");
            closeAllPinnedItem.Click += (s, e) => CloseAllPinnedImages();

            pinnedImagesItem.DropDownItems.AddRange(new ToolStripItem[]
            {
                showAllPinnedItem,
                hideAllPinnedItem,
                new ToolStripSeparator(),
                closeAllPinnedItem
            });

            // 设置
            var settingsItem = new ToolStripMenuItem("设置 (&T)")
            {
                Image = GetIcon("settings")
            };
            settingsItem.Click += (s, e) => ShowSettings();

            // 关于
            var aboutItem = new ToolStripMenuItem("关于 (&A)")
            {
                Image = GetIcon("info")
            };
            aboutItem.Click += (s, e) => ShowAbout();

            // 退出
            var exitItem = new ToolStripMenuItem("退出 (&X)")
            {
                Image = GetIcon("exit")
            };
            exitItem.Click += (s, e) => ExitApplication();

            // 添加菜单项
            _contextMenu.Items.AddRange(new ToolStripItem[]
            {
                clipboardHistoryItem,
                new ToolStripSeparator(),
                screenshotItem,
                pinnedImagesItem,
                new ToolStripSeparator(),
                settingsItem,
                aboutItem,
                new ToolStripSeparator(),
                exitItem
            });

            _notifyIcon!.ContextMenuStrip = _contextMenu;
        }

        private Icon GetApplicationIcon()
        {
            try
            {
                // 尝试从资源获取图标
                var iconPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Assets", "icon.ico");
                if (File.Exists(iconPath))
                {
                    return new Icon(iconPath);
                }

                // 使用默认图标
                return SystemIcons.Application;
            }
            catch
            {
                return SystemIcons.Application;
            }
        }

        private Image? GetIcon(string iconName)
        {
            try
            {
                // 尝试从资源获取小图标
                var iconPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Assets", $"{iconName}.png");
                if (File.Exists(iconPath))
                {
                    return Image.FromFile(iconPath);
                }

                // 返回null，让系统使用默认图标
                return null;
            }
            catch
            {
                return null;
            }
        }

        private void OnTrayIconDoubleClick(object? sender, EventArgs e)
        {
            ShowClipboardHistory();
        }

        private void OnTrayIconClick(object? sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                // 左键单击显示上下文菜单
                var method = typeof(NotifyIcon).GetMethod("ShowContextMenu",
                    BindingFlags.Instance | BindingFlags.NonPublic);
                method?.Invoke(_notifyIcon, null);
            }
        }

        private void ShowClipboardHistory()
        {
            try
            {
                System.Windows.Application.Current.Dispatcher.Invoke(() =>
                {
                    var mainWindow = _serviceProvider.GetRequiredService<MainWindow>();
                    mainWindow.WindowState = System.Windows.WindowState.Normal;
                    mainWindow.Show();
                    mainWindow.Activate();
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "显示剪贴板历史失败");
            }
        }

        private void TakeRegionScreenshot()
        {
            try
            {
                var screenshotService = _serviceProvider.GetRequiredService<ScreenshotService>();
                screenshotService.CaptureRegion();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "区域截图失败");
            }
        }

        private void TakeWindowScreenshot()
        {
            try
            {
                var screenshotService = _serviceProvider.GetRequiredService<ScreenshotService>();
                var screenshot = screenshotService.CaptureActiveWindow();
                if (screenshot != null)
                {
                    screenshotService.CaptureAndPin(screenshot);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "窗口截图失败");
            }
        }

        private void TakeFullScreenshot()
        {
            try
            {
                var screenshotService = _serviceProvider.GetRequiredService<ScreenshotService>();
                var screenshot = screenshotService.CaptureFullScreen();
                screenshotService.CaptureAndPin(screenshot);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "全屏截图失败");
            }
        }

        private void ShowAllPinnedImages()
        {
            try
            {
                var pinnedImageService = _serviceProvider.GetRequiredService<PinnedImageService>();
                var windows = pinnedImageService.GetActivePinnedWindows();
                foreach (var window in windows)
                {
                    window.Show();
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "显示所有钉图失败");
            }
        }

        private void HideAllPinnedImages()
        {
            try
            {
                var pinnedImageService = _serviceProvider.GetRequiredService<PinnedImageService>();
                var windows = pinnedImageService.GetActivePinnedWindows();
                foreach (var window in windows)
                {
                    window.Hide();
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "隐藏所有钉图失败");
            }
        }

        private void CloseAllPinnedImages()
        {
            try
            {
                var pinnedImageService = _serviceProvider.GetRequiredService<PinnedImageService>();
                pinnedImageService.CloseAllPinnedImages();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "关闭所有钉图失败");
            }
        }

        private void ShowSettings()
        {
            try
            {
                System.Windows.Application.Current.Dispatcher.Invoke(() =>
                {
                    var settingsWindow = _serviceProvider.GetRequiredService<Views.SettingsWindow>();
                    settingsWindow.Show();
                    settingsWindow.Activate();
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "显示设置窗口失败");
            }
        }

        private void ShowAbout()
        {
            MessageBox.Show(
                "桌面助手 v1.0\n\n" +
                "功能特性:\n" +
                "• 剪贴板历史记录管理\n" +
                "• 屏幕截图和桌面钉图\n" +
                "• 全局快捷键支持\n\n" +
                "快捷键:\n" +
                "• Ctrl+Shift+V: 显示剪贴板历史\n" +
                "• Ctrl+Shift+A: 区域截图\n" +
                "• Ctrl+Shift+W: 窗口截图\n" +
                "• Ctrl+Shift+S: 全屏截图",
                "关于桌面助手",
                MessageBoxButtons.OK,
                MessageBoxIcon.Information);
        }

        private void ExitApplication()
        {
            try
            {
                // 清理资源
                Dispose();

                // 停止应用程序
                System.Windows.Application.Current.Shutdown();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "退出应用程序失败");
            }
        }

        public void ShowNotification(string title, string message, ToolTipIcon icon = ToolTipIcon.Info)
        {
            try
            {
                _notifyIcon?.ShowBalloonTip(3000, title, message, icon);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "显示通知失败");
            }
        }

        public void Dispose()
        {
            try
            {
                _contextMenu?.Dispose();
                _notifyIcon?.Dispose();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "释放托盘资源失败");
            }
        }
    }
}